package com.cyq.blog.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyq.blog.entity.Admin;
import com.cyq.blog.entity.Blog;
import com.cyq.blog.entity.Category;
import com.cyq.blog.entity.Comment;
import com.cyq.blog.service.*;
import com.cyq.blog.util.MyConstant;
import com.cyq.blog.util.MybatisPlusUtil;
import com.cyq.blog.vo.ListCommentVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * AdminController class
 *
 * @author chenyeqing
 * @date 2021/5/14
 */
@Slf4j
@Controller
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private BlogService blogService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private ListCommentVoService listCommentVoService;

    /**
     * 跳转到管理员首页
     *
     * @return
     */
    @GetMapping("/admin")
    public String admin(Model model) {
        // 查询博客数
        int countBlog = blogService.count(null);
        log.debug("countBlog => " + countBlog);

        // 查询分类数
        int countCategory = categoryService.count(null);
        log.debug("countCategory => " + countCategory);

        // 查询回收站数量 自定义sql
        QueryWrapper<Blog> blogWrapper = new QueryWrapper<>();
        blogWrapper.eq("is_deleted", "1");
        int countRecycleBlog = blogService.countBlog(blogWrapper);
        log.debug("countRecycleBlog => " + countRecycleBlog);

        // 查询评论数量
        // 查询博客数
        int countComment = commentService.count(null);
        log.debug("countComment => " + countComment);

        model.addAttribute("blogCount", countBlog);
        model.addAttribute("countCategory", countCategory);
        model.addAttribute("countRecycleBlog", countRecycleBlog);
        model.addAttribute("countComment", countComment);
        return "admin/admin";
    }

    /**
     * 跳转到登录页面
     *
     * @return
     */
    @GetMapping("/admin/login")
    public String toLogin() {
        return "admin/login";
    }

    /**
     * 登录验证
     *
     * @param username 账号
     * @param password 密码
     * @param session  携带数据
     * @return
     */
    @PostMapping("/admin/login")
    public String login(@RequestParam("loginUsername") String username,
                        @RequestParam("loginPassword") String password,
                        HttpSession session
    ) {
        // 查询这条记录
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        Map<String, Object> map = new HashMap<>();
        map.put("login_username", username);
        map.put("login_password", password);
        wrapper.allEq(map);
        Admin admin = adminService.getOne(wrapper);

        // 校验账号密码
        if (ObjectUtils.isEmpty(admin)) {
            session.setAttribute("errorMsg", "账号或密码错误");
            return "/admin/login";
        } else {
            if ("0".equals(admin.getEnabled())) {
                session.setAttribute("admin", admin);
                return "redirect:/admin";
            } else {
                session.removeAttribute("errorMsg");
                session.setAttribute("errorMsg", "账号已被禁用");
                return "/admin/login";
            }
        }
    }

    /**
     * 退出登录
     *
     * @param session
     * @return
     */
    @GetMapping("/admin/logout")
    public String logout(HttpSession session) {
        System.out.println("==>" + session.getAttributeNames());
        session.removeAttribute("admin");
        // 返回首页
        return "redirect:/";
    }


    /**
     * 跳转 侧边栏 页面
     * @param url
     * @return
     */
    @GetMapping("/admin/{url}")
    public String jump(@PathVariable("url") String url, Model model,
                       @RequestParam(value = "current", defaultValue = "1") int current,
                       String searchName) {

        switch (url) {
            // 新增博客页面
            case "addBlog":
                log.info("====进入 新增博客 页面====");
                List<Category> categorys = categoryService.list(null);
                log.info("====进入 新增博客 页面====categorys====" + categorys);
                model.addAttribute("categories", categorys);
                break;

            // 管理博客页面
            case "listBlog":
                log.info("====进入 管理博客 页面====");
                QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();

                // 模糊查询内容 不等于空
                if (StringUtils.hasText(searchName)) {
                    blogQueryWrapper.like("blog_title", searchName);
                }

                Page<Blog> pages = blogService.page(MybatisPlusUtil.getPage(current), blogQueryWrapper);
                log.info("====进入 管理博客 页面====pages====>" + pages);
                model.addAttribute("blogs", pages);
                model.addAttribute("blogName", searchName);
                break;
            case "listCategory":
                log.info("====进入 分类管理 页面====");
                QueryWrapper<Category> categoryQueryWrapper2 = new QueryWrapper();
                if (StringUtils.hasText(searchName)) {
                    categoryQueryWrapper2.like("category_name", searchName);
                }
                Page<Category> categories = categoryService.page(MybatisPlusUtil.getPage(current), categoryQueryWrapper2);
                log.info("====进入 分类管理 页面====categories====>" + categories);
                model.addAttribute("categories", categories);
                model.addAttribute("categoryName", searchName);
                return "/admin/listCategory";
            case "recycleBin":
                log.info("====进入 博客回收站 页面====");
                // 查询器
                QueryWrapper<Blog> recycleQueryWrapper = new QueryWrapper<>();
                if (StringUtils.hasText(searchName)) {
                    recycleQueryWrapper.like("blog_title", searchName);
                }
                recycleQueryWrapper.eq("is_deleted", MyConstant.NUMBER_ONE);

                Page<Blog> recycleBins = blogService.page(MybatisPlusUtil.getPage(current), recycleQueryWrapper);
                log.info("====进入 博客回收站 页面====recycleBins====>" + recycleBins);
                model.addAttribute("recycleBins", recycleBins);
                model.addAttribute("recycleName", searchName);
                break;
            // 管理评论页面
            case "listComment":
                log.info("====进入 管理评论 页面====");
                //QueryWrapper<Comment> commentQueryWrapper = MybatisPlusUtil.isDeleted();
                QueryWrapper<ListCommentVo> commentQueryWrapper = new QueryWrapper<>();
                commentQueryWrapper.eq("c1.is_deleted", 0);

                // 模糊查询内容 不等于空
                if (StringUtils.hasText(searchName)) {
                    commentQueryWrapper.like("comment_body", searchName);
                }
                IPage<ListCommentVo> comments = listCommentVoService.listCommentTitle(MybatisPlusUtil.getPage(current), commentQueryWrapper);
                //Page<Comment> comments = commentService.page(MybatisPlusUtil.getPage(current), commentQueryWrapper);
                log.info("====进入 管理评论 页面====pages====>" + comments);
                model.addAttribute("comments", comments);
                model.addAttribute("commentName", searchName);
                break;
            default:
                log.info("====进入了 default ====");
                break;
        }
        return "/admin/" + url;
    }

    /**
     * 发布博客 添加博客
     * @return
     */
    @PostMapping("/admin/publish")
    public String release(Blog blog) {
        try {
            log.info("添加博客-req=>" + blog);
            // 设置默认值
            blog.setBlogViews(0L);
            // 默认显示图片
            if (!StringUtils.hasText(blog.getBlogCoverPhoto())) {
                blog.setBlogCoverPhoto("/admin/dist/img/rand/13.jpg");
            }
            // 根据分类ID 添加 分类名称
            Category category = categoryService.getById(blog.getBlogCategoryId());
            Assert.notNull(category, "没有这个id的分类内容");
            blog.setBlogCategoryName(category.getCategoryName());

            log.info("添加博客-res=>" + blog);
            boolean save = blogService.save(blog);

            log.info("添加博客状态==>" + save);
            log.info("添加博客成功==>" + blog);
        } catch (Exception e) {
            log.error("添加博客失败==>" + e);
        }
        return "redirect:/admin";
    }

    /**
     * 跳转到要修改的博客
     * @return
     */
    @GetMapping("/admin/updateBlog/{id}")
    public String toBlogUpdate(@PathVariable("id") String blogId, Model model) {
        Blog blog = blogService.getById(blogId);
        QueryWrapper<Category> queryWrapper = new QueryWrapper();
        List<Category> categories = categoryService.list(queryWrapper);
        Assert.notNull(blog, "没有Id为" + blogId + "的博客");
        model.addAttribute("blog", blog);
        model.addAttribute("categories", categories);
        return "/admin/updateBlog";
    }

    /**
     * 修改博客
     */
    @PostMapping("/admin/updateBlog")
    public String republish(Blog blog) {
        log.info("update=>" + blog);
        // 根据分类ID 设置 分类名称
        Category category = categoryService.getById(blog.getBlogCategoryId());
        Assert.notNull(category, "没有这个id的分类内容");
        blog.setBlogCategoryName(category.getCategoryName());

        blogService.updateById(blog);

        return "redirect:/admin/listBlog";
    }

    /**
     * 根据ID删除博客
     * @param blogId
     * @return
     */
    @GetMapping("/admin/removeBlog/{id}")
    public String removeBlog(@PathVariable("id") String blogId, String status,
                             @RequestParam(value = "current", defaultValue = "1") int current,String searchName, Model model) {
        log.info("进入 删除博客 方法");

        try {
            if ("1".equals(status)) {
                blogService.removeById(blogId);
                log.info("永久删除了id为：" + blogId + "的博客");
                jump("recycleBin", model, current, searchName);
                return "/admin/recycleBin";
            } else {
                UpdateWrapper<Blog> updateWrapper = new UpdateWrapper<>();
                updateWrapper.setSql("is_deleted = '1'");
                updateWrapper.eq("blog_id", blogId);
                blogService.update(updateWrapper);
                log.info("放入回收站了id为：" + blogId + "的博客");
                jump("listBlog", model, current, searchName);
                return "/admin/listBlog";
            }
        } catch (Exception e) {
            log.error(e.toString());
        }
        return "redirect:/admin";
    }

    /**
     * 恢复博客
     * @param blogId 博客id
     * @param current 恢复完以后回到回收站的那一页
     * @param searchName 恢复完以后返回搜索的值
     * @return
     */
    @GetMapping("/admin/resumeBlog/{id}")
    public String resumeBlog(@PathVariable("id") String blogId, int current,String searchName, Model model) {
        log.info("进入 恢复博客 方法");
        try {
            UpdateWrapper<Blog> updateWrapper = new UpdateWrapper<>();
            updateWrapper.setSql("is_deleted = '0'");
            updateWrapper.eq("blog_id", blogId);
            boolean update = blogService.update(updateWrapper);
            if (update) {
                log.info("恢复了id为：" + blogId + "的博客");
                // return "redirect:/admin/recycleBin?current=" + current + "&searchName=" + searchName;
                jump("recycleBin", model, current, searchName);
            }
        } catch (Exception e) {
            log.error("恢复失败=>" + e);
        }
        return "/admin/recycleBin";
    }


    /**
     * 根据ID删除评论
     * @param commentId
     * @return
     */
    @GetMapping("/admin/removeComment/{id}")
    public String removeBlog(@PathVariable("id") String commentId,
                             @RequestParam(value = "current", defaultValue = "1") int current,
                             String searchName, Model model) {
        log.info("进入 删除评论 方法");

        try {
            UpdateWrapper<Comment> updateWrapper = new UpdateWrapper<>();
            updateWrapper.setSql("is_deleted = '1'");
            updateWrapper.eq("comment_id", commentId);
            commentService.update(updateWrapper);
            log.info("删除了id为：" + commentId + "的评论");
            jump("listComment", model, current, searchName);
            return "/admin/listComment";
        } catch (Exception e) {
            log.error(e.toString());
        }
        return "redirect:/admin/listComment";
    }

    /**
     * 审核评论
     * @param commentId
     * @return
     */
    @GetMapping("/admin/reviewComment/{id}")
    public String reviewComment(@PathVariable("id") String commentId) {
        log.info("进入 审核评论 方法");
        log.info("commentId=>" + commentId);
        UpdateWrapper<Comment> updateWrapper = new UpdateWrapper<>();
        updateWrapper.setSql("comment_status = '1'");
        updateWrapper.eq("comment_id", commentId);
        commentService.update(updateWrapper);
        log.info("审核评论完成==>id:" + commentId);
        return "redirect:/admin/listComment";
    }


    @GetMapping("/admin/removeCategory/{categoryId}")
    public String removeCategory(@PathVariable("categoryId") String id) {
        log.info("删除分类=>" + id);
        categoryService.removeById(id);
        return "redirect:/admin/listCategory";
    }


}
